const dbasync=require("./sqlit3_async.js")
let filename=__dirname+"/key.sqlite"
const Cryptr = require('cryptr');
const cryptr = new Cryptr('myTotallySecretKey');

// const encryptedString = cryptr.encrypt('bacon');
// const decryptedString = cryptr.decrypt(encryptedString);

// console.log(encryptedString); // 2a3260f5ac4754b8ee3021ad413ddbc11f04138d01fe0c5889a0dd7b4a97e342a4f43bb43f3c83033626a76f7ace2479705ec7579e4c151f2e2196455be09b29bfc9055f82cdc92a1fe735825af1f75cfb9c94ad765c06a8abe9668fca5c42d45a7ec233f0
// console.log(decryptedString); // bacon
async function selectPassword(service, account) {
    let cmd=`select * from pwd where service='${service}' and account='${account}'` ;
    console.log(cmd);
    // return await dbasync.get(cmd)
    let one=await dbasync.get(cmd)
    console.log(one);
    try {
        if (one) one.password=cryptr.decrypt(one.password)
        return one
    } catch (TypeError) {
        console.log("error-----------------------")
        console.log(TypeError)
        return one;
    }
}
async function setPassword(service, account,password) {
    let r=await selectPassword(service,account)
    if(r){//find
        await updatePassword(service, account,password)
    }else{
        await createPassword(service, account,password).catch(
        function(err){
            console.error(err);
        })
    }
}
async function createPassword(service, account,password) {
    password=cryptr.encrypt(password)
    let cmd=`insert into pwd(service,account,password) values('${service}','${account}','${password}')` ;
    await dbasync.run(cmd);
}
async function updatePassword(service, account,password) {
    password=cryptr.encrypt(password)
    let cmd=`update pwd set password='${password}' where service='${service}' and account='${account}'` ;
    await dbasync.run(cmd);
}
async function deletePassword(service, account) {
    let cmd=`delete from  pwd where service='${service}' and account='${account}'` ;
    console.log("deletePassword")
    console.log(cmd)
    await dbasync.run(cmd);
}
async function createTable() {
    let cmd="CREATE TABLE pwd (service TEXT, account TEXT, password TEXT, PRIMARY KEY (service, account))"
    await dbasync.run(cmd);
}
async function selectAccount(service,callback) {
    let cmd=`select * from pwd where service='${service}'`
    console.log(cmd);
    let r=await dbasync.all(cmd)
    let r2=r.map(function(one,index){
        one.password=cryptr.decrypt(one.password);
        return one
    })
    return r2
}
async function init() {
    // body...
    console.log(await dbasync.open(filename))
}
// main()
module.exports={init,selectAccount,selectPassword,deletePassword,createTable,setPassword}